package com.medical_backend.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.medical_backend.entity.Division;
import com.medical_backend.entity.Result;
import com.medical_backend.entity.User;
import com.medical_backend.service.DivisionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/division")
public class DivisionController {
    @Autowired
    DivisionService divisionService;
    //获取区域信息列表
    @GetMapping("/list")
    public Result list(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String keyword) {
        QueryWrapper<Division> queryWrapper = new QueryWrapper<>();
        if (StringUtils.hasText(keyword)) {
            queryWrapper.lambda().like(Division::getId, keyword).or().like(Division::getDname, keyword);
        }
        Page<Division> pageInfo = divisionService.page(new Page<>(page, size),queryWrapper);
        return new Result("查询成功",pageInfo,200);
    }

    @PostMapping("/add")
    public Result add(@RequestBody Division division) {
        // 避免前端误传 id，手动置空
        division.setId(null);

        boolean save = divisionService.save(division);
        if (save) {
            return new Result("新增成功", division, 200);
        } else {
            return new Result("新增失败", null, 500);
        }
    }

    @PostMapping("/edit")
    public Result edit(@RequestBody Division division) {
        // 确保传入了 id，用于更新
        if (division.getId() == null) {
            return new Result("区域ID不能为空", null, 400);
        }

        boolean updated = divisionService.updateById(division);
        if (updated) {
            return new Result("修改成功", division, 200);
        } else {
            return new Result("修改失败", null, 500);
        }
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Long id) {
        boolean isDeleted = divisionService.removeById(id);
        if (isDeleted) {
            return new Result("删除成功", null, 200);
        } else {
            return new Result("删除失败: 区域信息不存在", null, 404);
        }
    }

//    // 获取子区域（用于级联懒加载）
//    @GetMapping("/children")
//    public Result getChildren(@RequestParam(required = false, defaultValue = "0") Long parentId) {
//        QueryWrapper<Division> queryWrapper = new QueryWrapper<>();
//        queryWrapper.lambda().eq(Division::getParent, parentId);
//
//        List<Division> divisions = divisionService.list(queryWrapper);
//
//        // 构造前端 Cascader 所需结构
//        List<Map<String, Object>> result = divisions.stream().map(d -> {
//            Map<String, Object> item = new HashMap<>();
//            item.put("id", d.getId());
//            item.put("name", d.getDname());
//            item.put("isLeaf", d.getLevel().equals("县")); // 如果是县级就是叶子节点
//            return item;
//        }).collect(Collectors.toList());
//
//        return new Result("查询成功", result, 200);
//    }

    @GetMapping("/children")
    public Result getChildrenByName(@RequestParam(required = false, defaultValue = "") String parentName) {
        Long parentId = 0L;

        if (!parentName.isEmpty()) {
            // 先根据名称查找父区域 ID
            Division parentDivision = divisionService.getOne(
                    new QueryWrapper<Division>().lambda().eq(Division::getDname, parentName)
            );
            if (parentDivision == null) {
                return new Result("未找到对应的父区域", Collections.emptyList(), 404);
            }
            parentId = parentDivision.getId();
        }

        // 再查找子区域
        List<Division> divisions = divisionService.list(
                new QueryWrapper<Division>().lambda().eq(Division::getParent, parentId)
        );

        List<Map<String, Object>> result = divisions.stream().map(d -> {
            Map<String, Object> item = new HashMap<>();
            item.put("id", d.getId());
            item.put("name", d.getDname());
            item.put("isLeaf", "县".equals(d.getLevel()));
            return item;
        }).collect(Collectors.toList());

        return new Result("查询成功", result, 200);
    }

}
